package com.qf.common.web.exception;

import com.qf.common.core.base.Codes;
import com.qf.common.core.base.R;
import com.qf.common.core.base.RetUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {


    @ExceptionHandler(BindException.class)
    public R bindExceptionHandler(BindException e){
        List<ObjectError> allErrors = e.getAllErrors();
        //处理异常信息集合
        List<String> errros = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            String msg = allError.getDefaultMessage();
            errros.add(msg);
        }
        return RetUtils.create(Codes.PARAM_ERROR, errros);
    }

    /**
     * 断言异常的统一处理
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public R illegalArgumentExceptionHandler(IllegalArgumentException illegalArgumentException){
        String message = illegalArgumentException.getMessage();
        return RetUtils.create(Codes.SERVER_ERROR.code, message, null);
    }


    @ExceptionHandler
    public R exceptionHandler(Throwable t){
        log.error("[Glabel-Exception] - 全局异常处理！", t);
        return RetUtils.create(Codes.SERVER_ERROR, null);
    }
}
